#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>

#define PORT    8000
#define MAX     3

int main(int argc, char * argv[])
{
    int listenfd, connfd;
    int opt = 1;
    struct sockaddr_in addr_in;
    int addr_len;
    char buffer[1024] = {0};

    addr_len = sizeof(addr_in);

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR|SO_REUSEPORT,
            &opt, sizeof(opt))) {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    addr_in.sin_family = AF_INET;
    addr_in.sin_addr.s_addr = INADDR_ANY;
    addr_in.sin_port = htons(PORT);

    if (bind(listenfd, (struct sockaddr *)&addr_in, sizeof(addr_in))) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    if (listen(listenfd, MAX) == -1) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    if ((connfd = accept(listenfd, (struct sockaddr *)&addr_in,
                    (socklen_t *)&addr_len)) == -1) {
        perror("accept failed");
        exit(EXIT_FAILURE);
    }

    if (read(connfd, buffer, 1024) == -1) {
        perror("read failed");
        exit(EXIT_FAILURE);
    }
    printf("[RECV]: %s\n", buffer);

    char * message = "hello from server";
    send(connfd, message, strlen(message), 0);
    printf("[SEND]: %s\n", message);

    close(connfd);
    close(listenfd);

    return 0;
}
